package framework.mq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * .消息接受者
 * 
 * @author JohnDeng 2018年11月14日下午2:31:16
 *
 */
public class QueueReceiver {
	// 默认连接用户名
private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
//private static final String USERNAME ="admin";
	// 默认连接密码
	private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
	//private static final String PASSWORD = "admin";
	// 默认连接地址
	private static final String BROKER_URL = ActiveMQConnection.DEFAULT_BROKER_URL;
	//private static final String BROKER_URL = "tcp://39.105.15.21:8161";

	public static void main(String[] args) {
		// 1获取创建工场，创建实例
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER_URL);
		Connection connection;
		try {
			connection = connectionFactory.createConnection();
			connection.start();
			//4.获取session(参数1：是否启动事务,参数2：消息确认模式)
			final Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
			Destination destination = session.createQueue("my-queue");
			MessageConsumer consumer = session.createConsumer(destination);
			int i = 0;
			while (i < 3) {
				i++;
				TextMessage message = (TextMessage) consumer.receive();
				session.commit();
				System.out.println("收到消 息：" + message.getText());
			}
			session.close();
			connection.close();

		} catch (JMSException e) {
			e.printStackTrace();
		}

	}
}
